<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0" />
    <title>常用中间件</title>
</head>

<body>
    <div>
        <h1> redux-thunk </h1>
        <p> npm install redux-thunk </p>
        <p> import thunk from 'redux-thunk' </p>
        <p>作用是允许我们代码在工作流程中加入异步代码</p>
    </div>
    <div>
        <h1> redux-saga </h1>
        <p> npm install 'redux-saga' </p>
        <p>作用是允许我们代码在工作流程中加入异步代码</p>
        <p>同时可以将异步操作从 Action Creator 文件中抽离出来，放在一个单独的文件中</p>
    </div>
    <div>
        <h1> redux-action </h1>
        <p> redux流程中大量粉样板代码读写很痛苦，使用redux-actions可以简化action和reducer的处理 </p>
        <p> npm install redux-actions </p>
    </div>

    <script>
        // 引入 redux-thunk
        import thunk from 'redux-thunk'
        // 在 store 中注册
        createStore(Reducer, applyMiddleware(thunk))
        // 在action中返回一个函数
        const loadPosta = () => async dispatch => {
            const posts = await axios.get('/api/posts').then(response => response.data)
            // 调用中间件返回的dispatch 触发其他action帮助我们把异步操作的结果返回给reducer
            dispatch({
                type: LOADPOSTSSUCCESS,
                payload: posts
            })
        }

        // 引入 redux-saga
        import createSagaMiddleware from 'redux-saga'
        const sagaMiddleware = createSagaMiddleware()
        // 在 store 中注册
        createStore(Reducer, applyMiddleware(sagaMiddleware))

        import {
            takeEvent, // 作用是用来接收action
            put // 用来触发另一个action
        } from 'redux-saga/effects'
        // 创建单独的文件来写异步代码
        function* load_posts() {
            const {
                data
            } = yield axios.get('/api/posts.json')
            yield put(load_posts_success(data))
        }

        export default function* postSaga() {
            yield takeEvery(LOAD_POSTS, load_posts)
        }

        // 启动 saga
        import postSage from './'
        sagaMiddleware.run(postSaga)


        // redux-actions
        // 创建 action
        import {
            createAction
        } from 'redux-actions'
        // 没有使用插件的写法
        // const increment = (payload) => ({ type: INCREMENT, payload })
        // 使用插件的写法
        const increment_action = createAction('increment')
        const decrement_action = createAction('decrement')

        // 在reducer中
        import {
            handActions as createReducer
        } from 'redux-actions'
        import {
            increment_action,
            decrement_action
        } from ''

        const initialStore = {
            conut: 0
        }
        const counterReducer = createReducer({
            [increment_action]: (state, action) => ({
                conut: state.conut + 1
            }),
            [decrement_action]: (state, action) => ({
                conut: state.count - 1
            })
        })
        export default counterReducer
    </script>
</body>

</html>